import smtplib
from email.mime.text import MIMEText

from ConfigFile.Varconfig import testData_path
from Util.ExcelOperate import ExcelOperate


class SendMail:

    def __init__(self,mail_host):
        '''
        构建邮件的smtp服务器的地址
        :param mail_host:
        '''
        self.mail_host = mail_host

    def send(self,title,content,sender,auth_code,receivers):
        '''
        发送该邮件
        :param title:
        :param content:
        :param sender:
        :param auth_code:
        :param receivers:
        :return:
        '''
        # 构建消息
        message = MIMEText(content,'html','utf-8')
        message['From'] = '{}'.format(sender)
        message['To'] = ','.join(receivers)
        message['Subject'] = title

        try:
            smtp_obj = smtplib.SMTP_SSL(self.mail_host,465)
            smtp_obj.login(sender,auth_code)
            smtp_obj.sendmail(sender,receivers,message.as_string())
            print('发送成功')
        except Exception as e:
            print(e)

def get_content():
    cotent = '''
    <html>
        <body>
            <h3>测试报告</h3>
            <table border='1'>
                <tr>
                    <th>编号</th>
                    <th>标题</th>
                    <th>是否通过</th>
                </tr>
                {}
            </table>
        </body>
    </html>

    '''
    details = ''
    ex = ExcelOperate()
    ex.load_workbook(testData_path)
    ex.get_sheet_by_name('Sheet1')
    for i in range(2,ex.get_rows_nums()+1):
        row_values = ex.get_row_values(i)
        print(row_values)

        details += '<tr><td>{}</td><td>{}</td><td>{}</td></tr>'.format(row_values[0],row_values[1],row_values[6])
    return cotent.format(details)
if __name__ == '__main__':
    # get_content()
    mail = SendMail('smtp.163.com')
    sender = ''
    receivers = ['325139646@qq.com','']
    title = 'ChyangTester'
    content = get_content()
    auth_code = ''
    mail.send(title,content,sender,auth_code,receivers)
